package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.RoleMenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.RoleMenu;
import com.itheima.service.SystemService;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 系统相关服务接口实现
 * @Author makun
 * @Date 2023/9/26 19:15
 * @Version 1.0
 */
@Service
public class SystemServiceImpl implements SystemService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<Menu> getMenusByUserId(Integer id) {
        return menuMapper.selectMenuByUserIdWithTree(id);
    }

    @Override
    public List<Menu> getAllMenusToTree() {
        return menuMapper.selectAllMenuToTree();
    }

    @Override
    public List<Menu> getAllMenus() {
        // 按照排序权重返回
        return menuMapper.selectList(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getPriority));
    }

    @Override
    public boolean editMenu(Menu menu) {
        return menuMapper.updateById(menu) == 1;
    }

    @Override
    public boolean saveMenu(Menu menu) {
        return menuMapper.insert(menu) == 1;
    }

    @Override
    public List<Menu> queryMenu(String queryStr) {
        return menuMapper.selectList(new LambdaQueryWrapper<Menu>().like(!StringUtils.isNullOrEmpty(queryStr),Menu::getName, queryStr));
    }

    @Override
    public boolean deleteMenuById(Integer id) {
        // 清空菜单与角色的关联
        roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId, id));
        // 删除菜单
        return menuMapper.deleteById(id) == 1;
    }
}
